package com.gdou.controller;

import com.gdou.commons.Result;
import com.gdou.dto.UserDto;
import com.gdou.dto.UserSearchDto;
import com.gdou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/*员工*/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/getUsersByPage")
    public Result getUsersByPage(
            @RequestParam(required = false,defaultValue = "1") Integer pageNum,
            @RequestParam(required = false,defaultValue = "10") Integer pageSize){
        return userService.findUsersByPage(pageNum,pageSize);
    }

    /*添加*/
    @RequestMapping("/addUser")
    public Result addUser(@Validated UserDto userDto, BindingResult bindingResult){
        System.out.println("添加ing");
        System.out.println(bindingResult.getAllErrors());
        //List<ObjectError> allErrors = bindingResult.getAllErrors();
        //for (ObjectError oe : bindingResult.getAllErrors()) {
        //    System.out.println(oe.toString());
        //}
        if (bindingResult.hasErrors()){
            return Result.DATA_FORMAT_ERROR;
        }
        return userService.saveUser(userDto);
    }

    /*单个删除*/
    @PostMapping("/cutOneUser")
    public Result cutOneUser(Long id){

        return userService.removeOneUser(id);
    }

    /*批量删除*/
    @RequestMapping("/cutManyUser")
    public Result cutManyUser(String id){
        return userService.removeManyUser(id);
    }

    /*修改*/
    @PostMapping("/editUser")
    public Result editUser(@Validated UserDto userDto,BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return Result.DATA_FORMAT_ERROR;
        }
        return userService.modifyUser(userDto);
    }

    /*多条件查询*/
    @RequestMapping("/getUsersBySearch")
    public Result getUsersBySearch(@Validated UserSearchDto userSearchDto,BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return Result.DATA_FORMAT_ERROR;
        }
        return userService.findUsersBySearch(userSearchDto);
    }
}
